﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utils.UDPHelps
{
    public class UDPSendHelp
    {
        static UDPSendHelp()
        {
            m_UdpClient= CreateUdpClient();
        }

        //创建用于发送的UDP端口号
        private static UdpClient CreateUdpClient()
        {
            UdpClient udpClient = null;
            //设置发送端口
            Random r = new Random(DateTime.Now.Millisecond);
            bool isSuccessSetPort = false;
            while (!isSuccessSetPort)
            {
                //源端口  目的端口
                int localPort = r.Next(0, 1000) % 1000 + 1000;
                try
                {
                    udpClient = new UdpClient(localPort);
                    isSuccessSetPort = true;
                }
                catch (Exception e)
                {
                    localPort = r.Next() % 1000 + 1000;
                }
            }
            //是否发送或接受广播
            udpClient.EnableBroadcast = true;
            //自发自收
            udpClient.MulticastLoopback = true;

            return udpClient;
        }

        private static UdpClient m_UdpClient;

        public static void Send(string ipAddress, int port, byte[] data)
        {
            try
            {
                int sendLength = m_UdpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ipAddress), port));
            }
            catch (Exception e)
            {

            }
        }
    }
}
